package com.qfedu.lc.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.lc.user.entity.MoneyLog;
import com.qfedu.lc.user.entity.Wallet;
import com.qfedu.lc.user.mapper.MoneyLogMapper;
import com.qfedu.lc.user.mapper.WalletMapper;
import com.qfedu.lc.user.service.WalletService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 6.用户钱包表 服务实现类
 * </p>
 *
 * @author KK
 * @since 2024-06-11
 */
@Service
public class WalletServiceImpl extends ServiceImpl<WalletMapper, Wallet> implements WalletService {

    @Autowired
    private WalletMapper walletMapper;

    @Autowired
    private MoneyLogMapper moneyLogMapper;

    @Override
    public boolean subWallet(Integer userId, Integer money) {
        // 1 查看账户余额
        QueryWrapper<Wallet> walletQueryWrapper = new QueryWrapper<>();
        walletQueryWrapper.eq("user_id", userId);
        Wallet wallet = walletMapper.selectOne(walletQueryWrapper);
        if (wallet == null || wallet.getMoney() < money) {
            return false;
        }

        // 2 削减账户余额
        wallet.setMoney(wallet.getMoney() - money);
        int num = walletMapper.updateById(wallet);
        if (num <= 0) {
            return false;
        }
        // 3 记录账户日志
        MoneyLog moneyLog = new MoneyLog();
        moneyLog.setUserId(userId);
        moneyLog.setMoney(money);
        moneyLog.setType(2);//减少
        moneyLog.setFlag("会员等级");
        moneyLog.setInfo("购买会员");
        moneyLog.setCtime(new Date());

        moneyLogMapper.insert(moneyLog);


        return true;
    }
}
